//
//  ViewController.m
//  Network
//
//  Created by wp w on 12-6-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "DLog.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    receivedData=[[NSMutableData alloc] initWithData:nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc {
    
	[receivedData release];
    
	[super dealloc];
}

#pragma mark - stringWithContentsOfURL:encoding:error:
- (IBAction)stringWithContentsOfURL {
    //+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
    //该函数，必须使用正确的字符集，否则返回错误
    //该函数时同步方法
    //示例一：最简单的
    {
        NSLog(@"example 1");
        NSString *symbol = @"AAPL,GOOG,MSFT,YHOO,PALM";
        NSString *urlString = [NSString stringWithFormat:@"http://finance.yahoo.com/d/quotes.csv?f=no&s=%@", symbol];
        NSURL *url = [NSURL URLWithString:urlString];
        NSString *quotes = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"result:\n%@", quotes);
        NSLog(@"done\n");
    }
    
    //示例二：演示NSError用法，该例子返回正确
    {
        NSLog(@"example 2");
        NSString *symbol = @"AAPL,GOOG,MSFT,YHOO,PALM";
        NSString *urlString = [NSString stringWithFormat:@"http://finance.yahoo.com/d/quotes.csv?f=no&s=%@", symbol];
        NSURL *url = [NSURL URLWithString:urlString];
        NSError *error=nil;
        NSString *quotes = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        if(quotes && !error)
        {
            NSLog(@"result:\n%@", quotes);
        }
        else {
            NSLog(@"error:%@", error);
        }
        NSLog(@"done\n");
    }
    
    //示例三：演示NSError用法
    //该例子因为编码问题，返回错误
    {
        NSLog(@"example 3");
        NSString *urlString = [NSString stringWithString:@"http://www.baidu.com"];
        NSURL *url = [NSURL URLWithString:urlString];
        NSError *error=nil;
        NSString *quotes = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        if(quotes && !error)
        {
            NSLog(@"result:\n%@", quotes);
        }
        else {
            NSLog(@"error:%@", error);
        }
        NSLog(@"done\n");
    }
    
    //NSStringEncoding
    //显示系统支持的编码
    {
        const NSStringEncoding *encodings = [NSString availableStringEncodings];
        NSStringEncoding encoding;
        int i = 0;
        while ((encoding = *encodings++) != 0) {
            NSLog(@"%d: %@ == 0x%x\n", i++, [NSString localizedNameOfStringEncoding:encoding], encoding);
        }
    }
    
    //NSStringEncoding
    //通过制定字符串获取相应的编码
    //+ (id)stringWithContentsOfURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error;
    //该函数，必须使用正确的字符集，否则返回错误
    {
        NSLog(@"example 4");
        NSString *urlString = [NSString stringWithString:@"http://www.baidu.com"];
        NSURL *url = [NSURL URLWithString:urlString];
        NSError *error=nil;
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSLog(@"%@ == 0x%x\n", [NSString localizedNameOfStringEncoding:enc], enc);
        NSString *quotes = [NSString stringWithContentsOfURL:url encoding:enc error:&error];
        if(quotes && !error)
        {
            NSLog(@"result:\n%@", quotes);
        }
        else {
            NSLog(@"error:%@", error);
        }
        NSLog(@"done\n");
    }
}

#pragma mark - NSURLRequest同步
//Get方法
- (IBAction)NSURLRequestTest {
    //使用NSURL创建NSURLRequest
    NSString *urlString = [NSString stringWithString:@"http://www.baidu.com"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *req= [NSURLRequest requestWithURL:url];
    
    //使用NSURLRequest创建一个连接NSURLConnection
    //且是一个同步连接
    NSError *error = nil;
	NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&error];
    if (data && !error) 
    {
        DLog(@"保存成功！");
        DlogDump(data);
    }
    else
    {
        DLogError(error);
    }
}

#pragma mark - NSURLRequest异步
//Get方法
- (IBAction)NSURLRequestTest1 {
    //使用NSURL创建NSURLRequest
    NSString *urlString = [NSString stringWithString:@"http://www.baidu.com"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *req=[[NSURLRequest alloc] initWithURL:url];
    

    
    //使用NSURLRequest创建一个连接NSURLConnection
	NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
	[req release];
	[conn release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
	UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Error" 
													  message:[error localizedDescription] 
													 delegate:nil 
											cancelButtonTitle:@"OK"
											otherButtonTitles:nil];
	[myAlert show];
	[myAlert release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSStringEncoding en = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 
	NSString *quotes = [[NSString alloc] 
						initWithBytes:[receivedData bytes] 
						length:[receivedData length] 
						encoding:en];
    DlogDump(receivedData);
	[quotes release];
}


#pragma mark - NSMutableURLRequest
//Get方法
- (IBAction)NSMutableURLRequestTest {
     //使用NSURL创建NSURLRequest
     NSString *urlString = [NSString stringWithString:@"http://www.baidu.com"];
     NSURL *url = [NSURL URLWithString:urlString];
     NSMutableURLRequest *req= [NSMutableURLRequest requestWithURL:url];
     [req setHTTPMethod:@"GET"];
     //[req setURL:url];   
     //[req addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];  
     //[req setHTTPBody:[@"some param" dataUsingEncoding:NSUTF8StringEncoding]];  
    
    /*
     //所构建的NSURLRequest具有一个依赖于缓存响应的特定策略，cachePolicy取得策略，timeoutInterval取得超时值
     NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
     NSURLRequest需要一个缓存参数来说明它请求的url何如缓存数据的，我们先看下它的CachePolicy类型。
     1、NSURLRequestUseProtocolCachePolicy NSURLRequest默认的cache policy，使用Protocol协议定义。
     2、NSURLRequestReloadIgnoringCacheData 忽略缓存直接从原始地址下载。
     3、NSURLRequestReturnCacheDataElseLoad 只有在cache中不存在data时才从原始地址下载。
     4、NSURLRequestReturnCacheDataDontLoad 只使用cache数据，如果不存在cache，请求失败；用于没有建立网络连接离线模式；
     5、NSURLRequestReloadIgnoringLocalAndRemoteCacheData：忽略本地和远程的缓存数据，直接从原始地址下载，与NSURLRequestReloadIgnoringCacheData类似。
     6、NSURLRequestReloadRevalidatingCacheData:验证本地数据与远程数据是否相同，如果不同则下载远程数据，否则使用本地数据。
     
     //设置缓存的大小为1M
     NSURLCache *urlCache = [NSURLCache sharedURLCache];
     [urlCache setMemoryCapacity:1*1024*1024];
     
     //创建一个url
     NSString *urlString = [NSString stringWithString:@"http://www.baidu.com"];
     NSURL *url = [NSURL URLWithString:urlString];
     
     //创建一个请求
     NSMutableURLRequest *request=[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
     
     //从请求中获取缓存输出
     NSCachedURLResponse *response = [urlCache cachedResponseForRequest:request];
     //判断是否有缓存
     if (response != nil){
     NSLog(@"如果有缓存输出，从缓存中获取数据");
     [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
     }
     
     //创建NSURLConnection
     NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
     */

     
     //使用NSURLRequest创建一个连接NSURLConnection
     //且是一个同步连接
     NSError *error = nil;
     NSURLResponse* response;
     NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
     if (data && !error) 
     {
         DLog(@"保存成功！");
         DlogDump(data);
     }
     else
     {
         DLogError(error);
     }
}

- (IBAction)NSMutableURLRequestTest1 {

}


@end
